package com.moli.iov.handle.alarm.biz.valid.alarm;

import com.moli.iov.handle.alarm.biz.valid.ValidHandler;
import com.moli.iov.handle.alarm.biz.utils.AlarmUtils;
import com.moli.iov.handle.alarm.constants.Constant;
import com.moli.iov.handle.alarm.enums.AlarmCodeEnum;
import com.moli.iov.handle.alarm.model.dto.AlarmDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * <p>
 *  报警 防抖 处理  拦截
 * </p>
 *
 * @author: zql
 * @Date: 2019/2/22 10:18
 */
@Slf4j
@Component
public class AntiShakeValidHandler implements ValidHandler<AlarmDto> {

    @Autowired
    private AlarmUtils alarmUtils;

    @Autowired
    private IgnoreValidHandler ignoreValidHandler;

    @Override
    public boolean doHandle(AlarmDto alarmDto) {

        if(!alarmDto.getIsAntiShake()){
            return true;
        }

        if(!isValidAlarm(alarmDto.getVin(), alarmDto.getAlarmCode())){

            log.error("报警 当前报警防抖校验未通过 vin:{} 报警类型：{}",
                    alarmDto.getVin(),
                    AlarmCodeEnum.getMsg(alarmDto.getAlarmCode()));

            return false;
        }

        return ignoreValidHandler.doHandle(alarmDto);
    }

    /**
     * 判断是否是有效报警  防抖
     * @param vin
     * @param alarmCode
     * @return
     */
    private boolean isValidAlarm(String vin, int alarmCode){

        int times = alarmUtils.getAlarmOn(vin, alarmCode);
        if(times <= Constant.ANTI_SHAKE_NON){

            alarmUtils.setAlarmOn(vin,
                    alarmCode,
                    Constant.ANTI_SHAKE_INIT);

            return false;
        }

        Long timesLong = alarmUtils.incrtAlarmOn(vin,
                alarmCode,
                Constant.ANTI_SHAKE_STEP);

        return timesLong >= Constant.ALARM_TIMES;
    }
}
